package com.example.mystore.dao;
import com.example.mystore.entity.Commodity;
import com.example.mystore.utils.LinkMySQL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

public class CommoditiesDao {
    public static HashMap<Integer,ArrayList<Commodity>> selectAll1(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        HashMap<Integer,ArrayList<Commodity>> hashMap = new HashMap<>();
        ArrayList<Integer> categoryList = new ArrayList<>();//获得分类列表
        try {
            conn = LinkMySQL.getConnection();
            String sql = "select distinct category from commodities ";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                categoryList.add(rs.getInt("category"));
            }
            for (int s : categoryList) {
                ArrayList<Commodity> commoditiesList = new ArrayList<>();
                String sql1 = "select * from commodities where category = ?";
                pstmt = conn.prepareStatement(sql1);
                pstmt.setInt(1, s);
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    System.out.println();
                    Commodity commodity = new Commodity(rs.getInt("id"), rs.getString("name"), rs.getString("img"), rs.getString("model"), rs.getString("introduction"), rs.getDouble("price"));
                    commoditiesList.add(commodity);
                }
                hashMap.put(s, commoditiesList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            LinkMySQL.release(rs,pstmt,conn);
        }
        return hashMap;
    }
}
